import axiosConfig from './axios.config';

export const get = (url: string, params?: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    filterParams(params);
    axiosConfig.get(url,{ params }).then(res => resolve(res)).catch(err => reject(err));
  });
};

export const put = (url: string, data?: any, params?: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    axiosConfig.put(url, data, {
      params,
      headers: {
        'Content-Type': data ? 'application/json;charset=UTF-8' : 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }).then(res => resolve(res)).catch(err => reject(err));
  });
};

export const post = (url: string, data?: any, params?: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    axiosConfig.post(url, data, {
      params,
      headers: {
        'Content-Type': data ? 'application/json;charset=UTF-8' : 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }).then(res => resolve(res)).catch(err => reject(err));
  });
};

export const deleted = (url: string, data?: any,params?: any): Promise<any> => {
  return new Promise((resolve,reject) => {
    axiosConfig.delete(url,{ data,params }).then(res => resolve(res)).catch(err => reject(err));
  });
};

const filterParams = (params: any): void => {
  if(params) {
    Object.keys(params).forEach(item => {
      if(params[item] === '') delete params[item];
    });
  }
};
